<?php

use SinoPHP\BbdBoss\Library\Etcd;
use Upfor\UpforPHP\Model;

require_once __DIR__ . '/../UpforPHP/bootstrap.php';
require_once __DIR__ . '/../vendor/autoload.php';

const DEFAULT_TTL = 30;

$params = $argv;

// $record = getDataFromDomain("www.bb.com", 1, '默认');
// print_r($record);die;
/**
 * 标志
 * 
 * @var null|string
 *      src 回源域名
 *      ser 内部域名
 *      all 全部
 */
$label = isset($params[1]) ? $params[1] : null;

if (empty($label) || !in_array($label, ['src', 'ser', 'all'])) {
    die("Notice:Need a param just like 'src','ser', 'all'!");
}

$thisWhere = [
    'is_delete' => 0,
    'etcd_status' => 0,
];
// 回源
if ('src' == $label) {
    $thisWhere["inner_domain_id"] = 0;
}
// 内部域名
if ('ser' == $label) {
    $thisWhere["inner_domain_id|!"] = 0;
}
$cols = [
    'layer_relation_id',
    'record_layer',
    'domain_id',
    'inner_domain_id',
    'record_line_name',
    'record'
];
// 解析关系
$relationList = model("CustomerDomainRelation")->getList($cols, $thisWhere);
if (empty($relationList)) {
    die("empty relationList!");
}
$totalCount = count($relationList);

// 域名列表
$domainIds = array_unique(array_column($relationList, 'domain_id'));
$domainList = getCustomeDomainList($domainIds);

$layerList = [
    Etcd::LAYER_LEVEL_EDGE,
    Etcd::LAYER_LEVEL_PARENT,
    Etcd::LAYER_LEVEL_SUPER,
    Etcd::LAYER_LEVEL_DYNAMICS
];
$etcdObj = Etcd::instance();

$relationData = array();
$successCount = 0;
foreach ($relationList as $domainInfo) {
    $etcdData = array();
    $etcdData = [
        'level' => $domainInfo['record_layer'],
        'line_type' => $domainInfo['record_line_name'],
        'host' => $domainInfo['record'],
        'ttl' => DEFAULT_TTL,
    ];

    if (empty($etcdData)) {
        continue;
    }

    try {
        $domainTemp = $domainList[$domainInfo['domain_id']]['domain_name'];
        $etcdObj->setDataToEtcd($domainTemp, $domainInfo['record_layer'], $domainInfo['record_line_name'], $etcdData);
        $relationData[] = [
            'layer_relation_id' => $domainInfo['layer_relation_id'],
            'etcd_status' => 1,
            'update_time' => time()
        ];
        $successCount ++;
    } catch (Exception $e) {
        $e->getMessage();
        continue;
    }
}

if (!empty($relationData)) {
    $dbRes = model("CustomerDomainRelation")->insert($relationData, true);
}

echo "ready total data {$totalCount}, success data num {$successCount};";

/**
 * 获取客户域名列表
 * 
 * @param  array $domainIds
 * @return array
 */
function getCustomeDomainList($domainIds) {
    // 客户域名信息
    $thisWhere = [
        'is_delete' => 0,
        'dnspod_id|!' => 0,
        'domain_id' => $domainIds
    ];
    $cols = [
        'domain_id',
        'domain_name',
        'source_domain_name',
    ];
    $domainList = model("CustomerDomain")->getList($cols, $thisWhere);
    if (empty($domainList)) {
        return [];
    }

    $newDomainList = array();
    foreach ($domainList as $domain) {
        $newDomainList[$domain['domain_id']] = $domain;
    }

    return $newDomainList;
}

/**
 * 获取etcd 域名解析记录信息
 * 
 * @param  string $domain 
 * @param  ineger $level 
 * @param  string $line  
 * @return string 
 */
function getDataFromDomain($domain, $level, $line) {
    $etcdObj = Etcd::instance();
    return $etcdObj->getDataFromEtcd($domain, $level, $line);
}
